package com.xiaozhengkeji.servlet.api.user;

import com.google.gson.JsonObject;
import com.xiaozhengkeji.servlet.dao.user.UserLogin;
import com.xiaozhengkeji.servlet.servlet.user.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet("/api/user/UserLoginApi")
public class UserLoginApi extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, String[]> dataMap = request.getParameterMap();
//        System.out.println(dataMap);
//        System.out.println("用户名:" + dataMap.get("username")[0]);
//        System.out.println("密码:" + dataMap.get("password")[0]);
//        System.out.println("邮箱:" + dataMap.get("email")[0]);
        UserLogin ul = new UserLogin();
        User u = ul.userLogin(dataMap.get("username")[0], dataMap.get("password")[0]);
        response.setHeader("Content-type", "application/json; charset=utf-8");
        //要创建JSON格式的数据，首先要创建一个整体的JSON的对象，作为一个容器
        JsonObject jsonObject = new JsonObject();
        if (u.getID() == null) {
            // 登陆失败
            jsonObject.addProperty("code", "404");
            jsonObject.addProperty("message", "未找到用户,或者账号密码错误!");
        } else {
            // 登陆成功
            jsonObject.addProperty("code", "1");
            jsonObject.addProperty("message", "登陆成功!");
            jsonObject.addProperty("user_id", u.getID());
            jsonObject.addProperty("user_email", u.getEmail());
            jsonObject.addProperty("user_form", u.getFORM());
        }
        out.write(jsonObject.toString());
    }
}
